<template>
  <basic-container>
    <div class="avue-crud">
      <!-- 搜索工作栏 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="队列名" prop="queueName">
          <el-input v-model="queryParams.queueName" placeholder="请输入队列名" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 操作工具栏 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-if="permissions.business_queue_add">新增
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <!-- 列表 -->
      <el-table v-loading="loading" :data="list" style="width: 100%">
        <el-table-column label="编号" align="center" prop="queueId" />
        <el-table-column label="队列名称" align="center" prop="queueName"/>
        <el-table-column label="队列标识" align="center" prop="queueKey"/>
        <el-table-column label="队列所在区域" align="center" prop="queueArea"/>
        <el-table-column label="日最大取号量" align="center" prop="ticketMaxLimit"/>
        <el-table-column label="描述" align="center" prop="queueDescribe"/>
        <el-table-column label="激活状态" align="center" prop="queueState" width="80">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.queueState" :active-value="0" :inactive-value="1"
                       @change="handleChangeState(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-if="permissions.business_queue_edit">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="bindWindow(scope.row)"
                       v-if="permissions.business_queue_bind_window">绑定窗口
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-if="permissions.business_queue_del">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 对话框(添加 / 修改) -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="队列名称" prop="queueName">
            <el-input v-model="form.queueName" placeholder="请输入队列名称"/>
          </el-form-item>
          <el-form-item label="队列标识" prop="queueKey">
            <el-input v-model="form.queueKey" placeholder="请输入队列标识"/>
          </el-form-item>
          <el-form-item label="队列所在区域" prop="queueArea">
            <el-input v-model="form.queueArea" placeholder="请输入队列所在区域"/>
          </el-form-item>
          <el-form-item label="日最大取号量" prop="ticketMaxLimit">
            <el-input v-model="form.ticketMaxLimit" placeholder="请输入日最大取号量"/>
          </el-form-item>
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number
              v-model="form.sortOrder"
              controls-position="right"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input type="textarea" autosize v-model="form.queueDescribe" placeholder="请输入描述"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!--   分配窗口弹窗   -->
      <el-dialog :title="transferTitle" :visible.sync="transferOpen" width="50%" append-to-body>
        <div style="text-align: center">
          <el-transfer
            style="text-align: left; display: inline-block"
            filterable
            :filter-method="filterMethod"
            filter-placeholder="请输入窗口名"
            v-model="transferTargetValue"
            :data="transferSourceData"
            :props="{
              key: 'windowId',
              label: 'windowName',
              disabled:'disabled'
            }"
            :titles="['窗口列表', '已选择窗口']"
            @change="selectChange">
          </el-transfer>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="bindWindowComplete" size="small">完成分配</el-button>
            <el-button @click="cancelBind" size="small">取 消</el-button>
          </div>
        </div>
      </el-dialog>

      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
                  @pagination="getList"/>
    </div>


  </basic-container>
</template>

<script>
import {fetchList, addObj, putObj, delObj, getObj, listQueueWindow, bindQueueWindow} from "@/api/queue/queue"
import {listAllWindow} from '@/api/queue/window'
import {mapGetters} from "vuex";

export default {
  name: "index",
  data() {
    return {
      // 队列id
      queueId: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 结果集合
      list: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        queueName: null,
      },
      // 是否弹出分配窗口
      transferOpen: false,
      // 分配窗口弹窗名称
      transferTitle: "",
      //源列表的数据 （source)
      transferSourceData: [],
      //目标列表的数据，源数据列表每一个都有一个对应的index，这里的数字就是列表里面的index,对应每一个数据
      transferTargetValue: [],
      // 表单校验
      rules: {
        queueName: [{required: true, message: "队列名称不能为空", trigger: "blur"}],
        queueKey: [{required: true, message: "队列标识不能为空", trigger: "blur"}],
        ticketMaxLimit: [{required: true, message: "日最大取号量不能为空", trigger: "blur"}],
        queueDescribe: [{required: true, message: "描述不能为空", trigger: "blur"}]
      }
    }
  },
  created() {
    this.getList()
  },
  computed: {
    ...mapGetters(["permissions"])
  },
  methods: {
    // 查询队列列表
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      fetchList(params).then(res => {
        this.list = res.data.data.records;
        this.total = res.data.data.total;
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.queueId != null) {
          putObj(this.form).then(response => {
            this.$message.success("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        addObj(this.form).then(response => {
          this.$message.success("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加队列";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.queueId;
      getObj(id).then(response => {
        this.form = response.data.data;
        this.open = true;
        this.title = "修改队列";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.queueId;
      this.$confirm('是否确认删除为："' + row.queueName + '"的数据项?').then(function () {
        return delObj(id);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },

    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        queueName: undefined,
        queueDescribe: undefined,
      };
      this.resetForm("form");
    },
    /** 更新状态操作 */
    handleChangeState(row) {
      let state = row.queueState;
      let statusState = state === 1 ? '激活' : '挂起';
      let param = {
        queueId: row.queueId,
        queueState: row.queueState
      }
      this.$confirm('是否确认' + statusState + '队列名字为"' + row.queueName + '"的数据项?').then(function () {
        return putObj(param);
      }).then(() => {
        this.getList();
        this.$message.success(statusState + "成功");
      }).catch(() => {
      });
    },
    filterMethod(query, item) {
      console.log("过滤搜索", query, item);
      return item.windowName.indexOf(query) > -1;
    },
    selectChange(value) {
      console.log("选择", value)
      console.log("选择结果集", this.transferTargetValue)
    },
    /** 队列绑定窗口 */
    bindWindow(row) {
      console.log("队列绑定窗口", row)
      this.queueId = row.queueId;
      this.transferOpen = true;
      this.transferTitle = "分配窗口";
      this.listAllWindows()
      this.listQueueWindow(row.queueId)
    },
    /** 完成绑定窗口 */
    bindWindowComplete() {
      let params = {
        queueId: this.queueId,
        windowIds: this.transferTargetValue
      }
      console.log("绑定窗口", params)

      bindQueueWindow(params).then(res => {
        if (res.data.code === 200 && res.data.data) {
          this.$message.success("修改成功");
          this.transferOpen = false;
        }
      })
    },
    /** 取消绑定 */
    cancelBind() {
      this.transferOpen = false;
    },
    /** 查询所有窗口 */
    listAllWindows() {
      listAllWindow().then(res => {
        console.log("所有窗口", res.data.data)
        this.transferSourceData = res.data.data
      })
    },
    /** 根据队列id查询该队列已经绑定的窗口 */
    listQueueWindow(queueId) {
      listQueueWindow(queueId).then(res => {
        console.log("根据队列id查询该队列已经绑定的窗口", res.data.data)
        this.transferTargetValue = res.data.data
      })
    },
  }
}
</script>

<style scoped>
.el-dialog .el-dialog__body {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
